<template>
  <el-container class="app_container flex">
    <Aside @handleNodeClick="handleNodeClick" />
    <div class="list_container flex both-100">
      <Breadcrumb :title="pageTitle" />
      <div class="content_container">
        <el-form ref="searchMap" :inline="true" :model="searchMap" class="serach_wrapper flex-space-between">
          <div class="search">
            <el-form-item prop="userName" size="small">
              <el-input v-model="searchMap.userName" placeholder="用户账户"></el-input>
            </el-form-item>
            <el-form-item prop="phonenumber" size="small">
              <el-input v-model="searchMap.phonenumber" placeholder="手机号码"></el-input>
            </el-form-item>
            <el-form-item prop="status" style="width: 120px" size="small">
              <el-select v-model="searchMap.status" placeholder="状态">
                <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="personnelCreateTime" style="width: 240px" size="small">
              <el-date-picker v-model="searchMap.personnelCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item class="flex">
              <el-button @click="handleSearch()" class="btn_primary">查询</el-button>
              <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
            </el-form-item>
          </div>
          <div class="edit">
            <el-form-item class="flex">
              <el-button @click="handleAdd()" class="btn_primary" icon="el-icon-plus">
                新增
              </el-button>
            </el-form-item>
          </div>

        </el-form>
        <!-- 表格 start -->
        <el-table :data="userList" stripe class="table_container" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
          <el-table-column label="用户账户" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible" width="120" />
          <el-table-column label="状态" align="center" key="status" v-if="columns[5].visible">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" disabled></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-hasPermi="['system:user:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleResetPwd" icon="el-icon-key" v-hasPermi="['system:user:resetPwd']">重置密码</el-dropdown-item>
                  <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check" v-hasPermi="['system:user:edit']">分配角色</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格 end -->
        <!-- 表格分页 start -->
        <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize" @change="initUserList"></Pagination>
        <!-- 表格分页 end -->
      </div>
    </div>

    <!-- 弹窗 新增/修改 start -->
    <div class="dialog_content">
      <el-dialog class="m_dialog" title="弹框" :visible.sync="DialogVisibleUser" width="800" append-to-body :close-on-click-modal="false">
        <el-form ref="form" :model="formModel" :rules="formRules" label-width="80px" size="small">
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户昵称" prop="nickName">
                <el-input v-model="formModel.nickName" placeholder="请输入用户昵称" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归属部门" prop="deptId">
                <treeselect v-model="formModel.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="formModel.phonenumber" placeholder="请输入手机号码" maxlength="11" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="formModel.email" placeholder="请输入邮箱" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="formModel.userId == undefined" label="用户账户" prop="userName">
                <el-input v-model="formModel.userName" placeholder="请输入用户账户" maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="formModel.userId == undefined" label="用户密码" prop="password">
                <el-input v-model="formModel.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户性别">
                <el-select v-model="formModel.sex" placeholder="请选择性别">
                  <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="formModel.status">
                  <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="岗位">
                <el-select v-model="formModel.postIds" multiple placeholder="请选择岗位">
                  <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId" :disabled="item.status == 1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色">
                <el-select v-model="formModel.roleIds" multiple placeholder="请选择角色">
                  <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" :disabled="item.status == 1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="formModel.remark" type="textarea" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="DialogVisibleUser = false" class="btn_cancel">取 消</el-button>
          <el-button type="primary" @click="submitFrom('addUserFrom')" class="btn_primary">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 弹窗 新增/修改 end -->
  </el-container>
</template>
<script>
import Aside from '@/components/Aside'
import Breadcrumb from '@/components/Breadcrumb'
import CustomForm from '@/components/CustomForm'
import BaseSelect from '@/components/BaseForm/BaseSelect.vue'
import BaseMultipleSelect from '@/components/BaseForm/BaseMultipleSelect.vue'
import BaseCheckboxGroup from '@/components/BaseForm/BaseCheckboxGroup.vue'
import BaseClick from '@/components/BaseForm/BaseClick.vue'
import BaseRadioGroup from '@/components/BaseForm/BaseRadioGroup.vue'
import { listUser, getUser, updateUser, delUser, addUser, deptTreeSelect, resetUserPwd } from '@/api'
export default {
  name: 'personnel',
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: {
    Aside,
    Breadcrumb,
    CustomForm,
    BaseSelect,
    BaseMultipleSelect,
    BaseCheckboxGroup,
    BaseClick,
    BaseRadioGroup,
  },
  data() {
    return {
      dataState: 0,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 用户列表
      userList: [],
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户账户`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      // dateRange  日期范围
      dateRange: null,
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 总条数
      total: 0,
      // 搜索参数
      searchMap: {
        pageNum: 1, // 当前页
        pageSize: 10,  // 默认条数
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 弹出框状态
      DialogVisibleUser: false,
      // 提交表单数据
      formModel: {},
      // 表但验证
      formRules: {
        userName: {
          required: true,
          message: '用户昵称不能为空',
          trigger: 'blur',
        },
        nickName: {
          required: true,
          message: '用户账户不能为空',
          trigger: 'blur',
        },
        password: [
          {
            required: true,
            message: '用户密码不能为空',
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (!/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/.test(value)) {
                return callback(new Error('用户密码长度8~20位，且至少含有数字、大写字母、小写字母和特殊符号其中三种'));
              }
              callback();
            },
            required: true,
            trigger: 'blur',
          }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      // 部门树
      deptOptions: undefined
    }
  },
  created() {
    this.initUserList()
    this.getDeptTree()
  },
  methods: {
    handleCommand(command, row) {
      console.log(command, row)
    },
    // 重置表单数据
    resetForm() {
      this.formModel = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
    },
    // 加载数据
    initUserList() {
      this.loading = true
      listUser(this.searchMap, this.dateRange).then(res => {
        const resp = res
        this.userList = resp.rows
        this.total = resp.total
        this.loading = false
      })
    },
    // 根据条件查询
    handleSearch() {
      this.searchMap.pageNum = 1
      this.initUserList();
    },
    //重置搜索栏数据
    handleReset() {
      this.$refs['searchMap'].resetFields()
      this.handleSearch()
    },
    // 修改数据
    handleEdit(row) {
      this.resetForm()
      const userId = row.userId
      getUser(userId).then(res => {
        if (res.code === 200) {
          const target = {}
          const keysToCopy = Object.getOwnPropertyNames(res.data).filter(key => key !== 'password')
          this.formModel = Object.assign(target, ...keysToCopy.map(key => ({ [key]: res.data[key] })))
          this.postOptions = res.posts;
          this.roleOptions = res.roles;
          this.$set(this.formModel, 'postIds', res.postIds)
          this.$set(this.formModel, 'roleIds', res.roleIds)
          this.DialogVisibleUser = true
          console.log('formModel', this.formModel)
        }
      });
    },
    // 新增用户信息
    handleAdd() {
      this.DialogVisibleUser = true
      this.resetForm()
      getUser().then(res => {
        if (res.code === 200) {
          this.postOptions = res.posts;
          this.roleOptions = res.roles;
          this.DialogVisibleUser = true
        }
      });
    },
    getpostOptions() {
      this.formItemConfig.forEach(item => {
        if (item.prop === 'postIds') {
          item.options = this.postOptions
          item.filedLabel = 'postName'
          item.filedValue = 'postId'
        }
      })
    },
    //点击删除
    handleDelete(row) {
      const userId = row.userId
      this.$confirm("确认删除这行数据吗？", "提示", {
        configButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          delUser(userId).then((response) => {
            console.log(response)
            this.initUserList()
          });
        })
        .catch(() => {
          console.log("点击了取消");
        });
    },
    // 提交表单判断是添加还是修改
    submitFrom() {
      try {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            const isAdd = this.formModel.userId === undefined
            let method = isAdd ? addUser : updateUser
            let message = isAdd ? '新增成功' : '修改成功'
            const response = await method(this.formModel)
            if (response && response.code === 200) {
              this.$message.success(message)
              this.initUserList()
              this.DialogVisibleUser = false
            }
          }
        })
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 节点点击触发
    handleNodeClick(data) {
      this.searchMap.deptId = data.id
      this.initUserList()
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^(?=.*[!@#$%^&*(),.?":{}|<>]).{7,20}$/,
        inputErrorMessage: "用户密码格式错误",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({ value }) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$message.success("修改成功，新密码是：" + value);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
  },
  computed: {
    pageTitle() {
      return '人员管理'
    },
  }
}
</script>

<style lang="less" scoped>
@import url("@/common/elementui.less");

.normal_dialog {
  background: url("@/assets/images/home/content.png") no-repeat;
}

.user_container {
  .user_main {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 0;

    .user_content {
      display: flex;
      flex-direction: column;
      padding: 15px 20px;
      height: calc(100% - 70px);
      background: url("@/assets/images/home/content.png") no-repeat;
      background-size: cover;

      .content_footer {
        text-align: right;
        height: 32px;
      }
    }
  }

  .dialog_content {
    padding: 5px;
  }
}
</style>